package Classic150;

public class 矩阵置零 {
    /*
        使用第一列与第一行作为标记变量判断各行各列是否存在0，并使用两个flag判断第一列、行是否存在0
     */
    public void setZeroes(int[][] matrix) {
        boolean rowFlag = false, colFlag = false;
        int rowLen = matrix[0].length, colLen = matrix.length;
        for (int i = 0; i < rowLen; i++) {
            if (matrix[0][i] == 0) {
                rowFlag = true;
                break;
            }
        }
        for (int i = 0; i < colLen; i++) {
            if (matrix[i][0] == 0) {
                colFlag = true;
                break;
            }
        }
        for (int i = 1; i < colLen; i++) {
            for (int j = 1; j < rowLen; j++) {
                if (matrix[i][j] == 0) matrix[i][0] = matrix[0][j] = 0;
            }
        }
        for (int i = 1; i < colLen; i++) {
            for (int j = 1; j < rowLen; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
            }
        }
        if (rowFlag) for (int i = 0; i < rowLen; i++) matrix[0][i] = 0;
        if (colFlag) for (int i = 0; i < colLen; i++) matrix[i][0] = 0;
    }
}
